# # def filter_lines_with_phrase(input_file, output_file, phrase):
# #     try:
# #         # 打开输入文件并读取内容
# #         with open(input_file, 'r', encoding='utf-8') as file:
# #             lines = file.readlines()
        
# #         # 只保留包含指定短语的行
# #         filtered_lines = [line for line in lines if phrase in line]
        
# #         # 将结果写入新的输出文件
# #         with open(output_file, 'w', encoding='utf-8') as file:
# #             file.writelines(filtered_lines)
        
# #         print(f'Successfully filtered the lines and saved the updated content to {output_file}')
    
# #     except Exception as e:
# #         print(f'An error occurred: {e}')

# # # 输入文件名和输出文件名
# # input_file = 'output.txt'
# # output_file = 'processed_output.txt'

# # # 要保留的短语
# # phrase = 'loop_br:'

# # # 调用函数处理文件
# # filter_lines_with_phrase(input_file, output_file, phrase)

# import pandas as pd

# def txt_to_excel(input_file, output_file):
#     try:
#         # 打开输入文件并读取内容
#         with open(input_file, 'r', encoding='utf-8') as file:
#             lines = file.readlines()
        
#         # 只保留包含指定短语的行
#         filtered_lines = [line.strip() for line in lines if 'loop_br:' in line]
        
#         # 解析每一行，并将数据存入字典列表
#         data = []
#         for line in filtered_lines:
#             parts = line.split(',')
#             entry = {
#                 'loop_br': parts[0].split(':')[1].strip(),
#                 'remaining_num': parts[1].split(':')[1].strip(),
#                 'node_num_changing': parts[2].split(':')[1].strip()
#             }
#             data.append(entry)
        
#         # 使用pandas将数据转换为DataFrame并写入Excel文件
#         df = pd.DataFrame(data)
#         df.to_excel(output_file, index=False)
        
#         print(f'Successfully converted the text file to {output_file}')
    
#     except Exception as e:
#         print(f'An error occurred: {e}')

# # 输入文件名和输出文件名
# input_file = 'processed_output.txt'
# output_file = 'communication_load_output.xlsx'

# # 调用函数处理文件
# txt_to_excel(input_file, output_file)


# import matplotlib.pyplot as plt


# def read_data(file_path):
#     x = []
#     y1 = []
#     y2 = []
#     y3 = []
#     y4 = []

#     with open(file_path, 'r') as f:
#         next(f)  # 跳过列名
#         for line in f:
#             data = line.strip().split(',')
#             x.append(float(data[0]))
#             y1.append(float(data[1]))
#             y2.append(float(data[2]))
#             y3.append(float(data[3]))
#             y4.append(float(data[4]))

#     return x, y1, y2, y3, y4


# def data_show(x, y1, y2, y3, y4, txt_name):

#     parts = txt_name.split("_")
#     first_part = parts[0]
#     second_part = parts[1]

#     plt.plot(x, y1, label='BR', marker='o', markersize=10, linewidth=1)  
#     # plt.plot(x, y2, label='Pro_first')  
#     plt.plot(x, y3, label='Step_first', marker='H', markersize=10, linewidth=1)  
#     plt.plot(x, y4, label='Remaining_first', marker='x', markersize=10, linewidth=1)  
#     plt.xlabel(f'{second_part}')
#     plt.ylabel(f'{first_part} (qbqs)')
#     # plt.title('Throughput') 
#     plt.legend()
#     plt.xticks(x)  # 设置横坐标刻度为所有的 x 值
#     plt.grid(True)  # 启用网格辅助
#     plt.savefig(f'./data/experiment_images/{txt_name}.png')
#     plt.clf()  # 清除当前图像
#     plt.show()


# name_list = [
#     'throughput_connectivity',
#     'throughput_el_remaining',
#     'throughput_scale',
#     'throughput_successPro',
#     'throughput_workload',    
#     'waiting_connectivity',
#     'waiting_el_remaining',
#     'waiting_scale',
#     'waiting_successPro',
#     'waiting_workload',
#     'waste_connectivity',
#     'waste_el_remaining',
#     'waste_scale',
#     'waste_successPro',
#     'waste_workload'
# ]

# for txt_name in name_list:
#     print(txt_name)
#     file_path = f'./data/experiment_data/{txt_name}.txt'
#     x, y1, y2, y3, y4 = read_data(file_path)
#     # print(x, y1, y2, y3, y4)
#     data_show(x, y1, y2, y3, y4, txt_name)

# import pandas as pd
# import matplotlib.pyplot as plt

# def read_data(file_path):
#     df = pd.read_excel(file_path)
#     return df

# def data_show(df, txt_name):
#     parts = txt_name.split("_")
#     first_part = parts[0]
#     second_part = parts[1]

#     x = df.iloc[:, 0]  # 第一列作为横坐标
#     y_columns = df.columns[1:]  # 排除第一列，包含剩余所有列

#     markers = ['o','h', 's', '^']  # 定义不同曲线的标记样式
#     # markers = ['s', 'o']
#     colors = ['blue', 'green', 'red', 'purple']

#     # 自定义标签列表，可以根据需要修改
#     custom_labels = ['DMES', 'Label 2', 'PPME', 'PIER']

#     plt.figure()
#     min_y = float('inf')
#     max_y = float('-inf')
#     for i, col in enumerate(y_columns):
#         if i == 1:  # 忽略第三列
#             continue
#         marker = markers[i % len(markers)]  # 使用取模运算轮流选择标记样式
#         color = colors[i % len(colors)]  # 使用取模运算轮流选择颜色
#         label = custom_labels[i % len(custom_labels)]  # 使用取模运算轮流选择自定义标签
#         plt.plot(x, df[col], label=label, marker=marker, markersize=10, linewidth=2.5)
#         min_y = min(min_y, df[col].min())
#         max_y = max(max_y, df[col].max())
    
#     if second_part == 'scale':
#         plt.xlabel(f'Number of nodes',fontsize=16)
#     elif second_part == 'workload':
#         plt.xlabel(f'Number of SD pairs',fontsize=16)
#     elif second_part == 'connectivity':
#         plt.xlabel(f'Network connectivity (β in the Waxmax model)',fontsize=16)
#     elif second_part == 'successPro':
#         plt.xlabel(f'Success prob. to create an EL',fontsize=16)    
#     elif second_part == 'el':
#         plt.xlabel(f'Number of sustainable time slots for EL',fontsize=16)    

#     if first_part == 'throughput':
#         plt.ylabel(f'Throughput(qbqs)',fontsize=16)
#     elif first_part == 'waiting':
#         plt.ylabel(f'Number of time slots',fontsize=16)
#     elif first_part == 'waste':
#         plt.ylabel(f'Number of unused EL ',fontsize=16)    

#     plt.legend(fontsize=15)  
#     plt.grid(True)  # 启用网格辅助

#     plt.xticks(x)
#     range_padding = 0.2*(max_y - min_y)
#     if first_part == "waste":
#         plt.ylim(min_y - 0.5*range_padding, max_y + 2*range_padding)
#     elif first_part == "waiting":
#         plt.ylim(min_y - 0.5*range_padding, max_y + 2*range_padding)
#     else:
#         plt.ylim(min_y - 1.1*range_padding, max_y + 1.4*range_padding)  # 设置纵坐标显示范围

#     plt.savefig(f'./data/experiment_images/{txt_name}.svg')
#     # plt.savefig(f'./data/experiment_images/{txt_name}.png')
#     plt.clf()  # 清除当前图像
#     plt.show()

# name_list = [
#     'throughput_connectivity',
#     'throughput_el_remaining',
#     'throughput_scale',
#     'throughput_successPro',
#     'throughput_workload',    
#     'waiting_connectivity',
#     'waiting_el_remaining',
#     'waiting_scale',
#     'waiting_successPro',
#     'waiting_workload',
#     'waste_connectivity',
#     'waste_el_remaining',
#     'waste_scale',
#     'waste_successPro',
#     'waste_workload'
# ]

# for txt_name in name_list:
#     print(txt_name)
#     file_path = f'./data/data_to_excel/{txt_name}.xlsx'
#     df = read_data(file_path)
#     data_show(df, txt_name)

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np


def read_data(file_path):
    df = pd.read_excel(file_path)
    return df

def data_show(df, txt_name):
    parts = txt_name.split("_")
    first_part = parts[0]
    second_part = parts[1]

    x = df.iloc[:, 0]  # 第一列作为横坐标
    y_columns = df.columns[1:]  # 排除第一列，包含剩余所有列

    markers = ['o','h', 's', '^']  # 定义不同曲线的标记样式
    colors = ['blue', 'green', 'red', 'purple']

    # 自定义标签列表，可以根据需要修改
    # custom_labels = ['DMES', 'Label 2', 'PPME', 'PIER']

    plt.figure()
    min_y = float('inf')
    max_y = float('-inf')
    for i, col in enumerate(y_columns):
        if i == 1:  # 忽略第三列
            continue
        marker = markers[i % len(markers)]  # 使用取模运算轮流选择标记样式
        color = colors[i % len(colors)]  # 使用取模运算轮流选择颜色
        # label = custom_labels[i % len(custom_labels)]  # 使用取模运算轮流选择自定义标签
        plt.plot(x, df[col], marker=marker, markersize=10, linewidth=2.5)
        min_y = min(min_y, df[col].min())
        max_y = max(max_y, df[col].max())
    
    # if second_part == 'scale':
    #     plt.xlabel(f'Number of nodes', fontsize=16)
    # elif second_part == 'workload':
    #     plt.xlabel(f'Number of SD pairs', fontsize=16)
    # elif second_part == 'connectivity':
    #     plt.xlabel(f'Network connectivity (β in the Waxmax model)', fontsize=16)
    # elif second_part == 'successPro':
    #     plt.xlabel(f'Success prob. to create an EL', fontsize=16)
    # elif second_part == 'el':

    plt.rcParams['pdf.fonttype'] = 42

    plt.xlabel(f'Number of nodes', fontsize=16)

    # if first_part == 'throughput':
    #     plt.ylabel(f'Throughput(qbqs)', fontsize=18)
    # elif first_part == 'waiting':
    #     plt.ylabel(f'Number of time slots', fontsize=18)
    # elif first_part == 'waste':
    plt.ylabel(f'Number of Iterations', fontsize=18)

    plt.legend(fontsize=15)  
    plt.grid(True)  # 启用网格辅助

    # 处理 x 中的 NaN 值
    x = x.dropna()
    plt.xticks(x, fontsize=15)  # 设置 x 轴刻度字体大小
    plt.yticks(fontsize=15)  # 设置 y 轴刻度字体大小
    
    range_padding = 0.2 * (max_y - min_y)
    if first_part == "waste":
        plt.ylim(min_y - 0.5 * range_padding, max_y + 2 * range_padding)
    elif first_part == "waiting":
        plt.ylim(min_y - 0.5 * range_padding, max_y + 2 * range_padding)
    else:
        plt.ylim(min_y - 1.1 * range_padding, max_y + 1.4 * range_padding)  # 设置纵坐标显示范围

    # 调整边距
    plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.1) 

    # plt.savefig(f'./communication_load_output.svg', bbox_inches='tight')
    plt.savefig(f'./communication_load_output.png', bbox_inches='tight')
    plt.clf()  # 清除当前图像
    plt.show()

# name_list = [
#     'throughput_connectivity',
#     'throughput_el_remaining',
#     'throughput_scale',
#     'throughput_successPro',
#     'throughput_workload',    
#     'waiting_connectivity',
#     'waiting_el_remaining',
#     'waiting_scale',
#     'waiting_successPro',
#     'waiting_workload',
#     'waste_connectivity',
#     'waste_el_remaining',
#     'waste_scale',
#     'waste_successPro',
#     'waste_workload'
# ]

# for txt_name in name_list:
    # print(txt_name)
file_path = f'./communication_load_output.xlsx'
df = read_data(file_path)
data_show(df, 'communication_load_output')




